package com.xdhl.fu.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xdhl.fu.common.core.constant.event.EmailSendConstants;
import com.xdhl.fu.common.core.exception.ServiceException;
import com.xdhl.fu.email.api.domain.TextEmail;
import com.xdhl.fu.email.api.enums.EmailType;
import com.xdhl.fu.member.rocketmq.MsgProducer;
import com.xdhl.fu.member.service.IEmailService;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Random;

@Service
public class EmailServiceImpl implements IEmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Resource
    private MsgProducer msgProducer;

    public String send(String email) {
        try {
            // 生成随机验证码
            Random random = new Random();
            StringBuilder builder = new StringBuilder();
            for (int i = 1; i <= 6; i++) {
                builder.append(random.nextInt(10));
            }
            String authCode = builder.toString();
            TextEmail textEmail = new TextEmail();
            textEmail.setTo(email);
            textEmail.setSubject("邮箱验证码");
            textEmail.setText(String.format("尊敬的用户：您好！您的邮箱验证码为：%s (有效期为5分钟)", authCode));
            textEmail.setEmailType(EmailType.VERIFICATION_CODE);
            Message message = new Message();
            message.setTopic(EmailSendConstants.TOPIC);
            message.setTags("");
            message.setBody(JSONObject.toJSONString(textEmail).getBytes(StandardCharsets.UTF_8));
            msgProducer.getMqProducer().send(message);
            return authCode;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException("验证码发送失败，请稍后再试。");
        }

    }
}
